#!/usr/bin/env python3
"""
Seasoning Store Management System - Flask API Server.
"""

from flask import Flask, jsonify, request, send_file
from flask_cors import CORS
import csv
import io
from datetime import datetime
from seasoning_store import (
    StoreDatabase,
    StoreSystem,
    DATA_FILE,
    _format_date,
    _parse_date,
)

app = Flask(__name__, static_folder='static', static_url_path='')
CORS(app)  # 允许跨域请求

# 初始化数据库和系统
db = StoreDatabase(DATA_FILE)
system = StoreSystem(db)


@app.route("/api/employees", methods=["GET"])
def get_employees():
    """获取所有员工及其薪资信息"""
    employees = []
    for emp in system.db.employees.values():
        employees.append({
            "employee_id": emp.employee_id,
            "name": emp.name,
            "role": emp.role,
            "contact": emp.contact,
            "base_salary": emp.base_salary,
            "performance_target": emp.performance_target,
            "performance_score": emp.performance_score,
            "salary": emp.salary(),
            "guarantor_name": emp.guarantor_name,
            "guarantor_contact": emp.guarantor_contact,
            "guarantor_relation": emp.guarantor_relation,
        })
    return jsonify({"success": True, "data": employees})


@app.route("/api/employees", methods=["POST"])
def add_employee():
    """添加新员工"""
    try:
        data = request.json
        system.add_employee(
            employee_id=data["employee_id"],
            name=data["name"],
            role=data["role"],
            contact=data["contact"],
            base_salary=float(data["base_salary"]),
            performance_target=float(data["performance_target"]),
            guarantor_name=data.get("guarantor_name", ""),
            guarantor_contact=data.get("guarantor_contact", ""),
            guarantor_relation=data.get("guarantor_relation", ""),
        )
        return jsonify({"success": True, "message": "员工添加成功"})
    except Exception as e:
        return jsonify({"success": False, "message": str(e)}), 400


@app.route("/api/employees/<employee_id>", methods=["PUT"])
def update_employee(employee_id):
    """更新员工信息"""
    try:
        data = request.json
        system.update_employee_info(
            employee_id=employee_id,
            role=data.get("role"),
            contact=data.get("contact"),
            base_salary=float(data["base_salary"]) if "base_salary" in data else None,
            performance_target=float(data["performance_target"]) if "performance_target" in data else None,
            guarantor_name=data.get("guarantor_name"),
            guarantor_contact=data.get("guarantor_contact"),
            guarantor_relation=data.get("guarantor_relation"),
        )
        return jsonify({"success": True, "message": "员工信息更新成功"})
    except Exception as e:
        return jsonify({"success": False, "message": str(e)}), 400


@app.route("/api/employees/<employee_id>", methods=["DELETE"])
def delete_employee(employee_id):
    """删除员工"""
    try:
        system.delete_employee(employee_id)
        return jsonify({"success": True, "message": "员工删除成功"})
    except Exception as e:
        return jsonify({"success": False, "message": str(e)}), 400


@app.route("/api/employees/<employee_id>/performance", methods=["POST"])
def update_performance(employee_id):
    """更新员工绩效"""
    try:
        data = request.json
        delta = float(data["delta"])
        system.update_performance(employee_id, delta)
        return jsonify({"success": True, "message": "绩效更新成功"})
    except Exception as e:
        return jsonify({"success": False, "message": str(e)}), 400


@app.route("/api/products", methods=["GET"])
def get_products():
    """获取所有产品库存信息"""
    products = []
    for prod in system.db.products.values():
        products.append({
            "sku": prod.sku,
            "name": prod.name,
            "category": prod.category,
            "quantity": prod.quantity,
            "reorder_threshold": prod.reorder_threshold,
            "expires_on": _format_date(prod.expires_on),
            "price": prod.price,
            "needs_restock": prod.needs_restock(),
            "needs_expiry_warning": prod.needs_expiry_warning(),
        })
    return jsonify({"success": True, "data": products})


@app.route("/api/products", methods=["POST"])
def add_product():
    """添加新产品"""
    try:
        data = request.json
        system.add_product(
            sku=data["sku"],
            name=data["name"],
            category=data["category"],
            quantity=int(data["quantity"]),
            reorder_threshold=int(data["reorder_threshold"]),
            expires_on=data["expires_on"],
            price=float(data.get("price", 200.0)),  # 默认单价200
        )
        return jsonify({"success": True, "message": "产品添加成功"})
    except Exception as e:
        return jsonify({"success": False, "message": str(e)}), 400


@app.route("/api/products/<sku>", methods=["DELETE"])
def delete_product(sku):
    """删除产品"""
    try:
        system.delete_product(sku)
        return jsonify({"success": True, "message": "产品删除成功"})
    except Exception as e:
        return jsonify({"success": False, "message": str(e)}), 400


@app.route("/api/products/<sku>/restock", methods=["POST"])
def restock_product(sku):
    """补货产品，可选更新过期日期和单价"""
    try:
        data = request.json
        quantity = int(data["quantity"])
        expires_on = data.get("expires_on")  # 可选参数
        price = float(data["price"]) if data.get("price") else None  # 可选参数
        system.restock(sku, quantity, expires_on, price)
        message = "补货成功"
        updates = []
        if expires_on:
            updates.append("过期日期已更新")
        if price is not None:
            updates.append("单价已更新")
        if updates:
            message += "，" + "、".join(updates)
        return jsonify({"success": True, "message": message})
    except Exception as e:
        return jsonify({"success": False, "message": str(e)}), 400


@app.route("/api/products/<sku>/expiry", methods=["PUT"])
def update_product_expiry(sku):
    """更新产品过期日期"""
    try:
        data = request.json
        expires_on = data["expires_on"]
        system.update_product_expiry(sku, expires_on)
        return jsonify({"success": True, "message": "过期日期更新成功"})
    except Exception as e:
        return jsonify({"success": False, "message": str(e)}), 400


@app.route("/api/sales", methods=["POST"])
def record_sale():
    """记录销售"""
    try:
        data = request.json
        system.record_sale(
            sku=data["sku"],
            quantity=int(data["quantity"]),
            employee_id=data.get("employee_id"),
        )
        return jsonify({"success": True, "message": "销售记录成功"})
    except Exception as e:
        return jsonify({"success": False, "message": str(e)}), 400


@app.route("/api/alerts/expiring", methods=["GET"])
def get_expiring_products():
    """获取即将过期的产品"""
    products = []
    for prod in system.db.products.values():
        if prod.needs_expiry_warning():
            products.append({
                "sku": prod.sku,
                "name": prod.name,
                "expires_on": _format_date(prod.expires_on),
            })
    return jsonify({"success": True, "data": products})


@app.route("/api/alerts/low-stock", methods=["GET"])
def get_low_stock_products():
    """获取低库存产品"""
    products = []
    for prod in system.db.products.values():
        if prod.needs_restock():
            products.append({
                "sku": prod.sku,
                "name": prod.name,
                "quantity": prod.quantity,
                "reorder_threshold": prod.reorder_threshold,
            })
    return jsonify({"success": True, "data": products})


@app.route("/api/stats", methods=["GET"])
def get_stats():
    """获取统计信息"""
    total_employees = len(system.db.employees)
    total_products = len(system.db.products)
    low_stock_count = sum(1 for p in system.db.products.values() if p.needs_restock())
    expiring_count = sum(1 for p in system.db.products.values() if p.needs_expiry_warning())
    
    return jsonify({
        "success": True,
        "data": {
            "total_employees": total_employees,
            "total_products": total_products,
            "low_stock_count": low_stock_count,
            "expiring_count": expiring_count,
        }
    })


@app.route("/api/sales/history", methods=["GET"])
def get_sales_history():
    """获取销售历史记录"""
    try:
        limit = request.args.get("limit", 100, type=int)
        sales = system.get_sales_history(limit)
        sales_data = [{
            "sale_id": sale.sale_id,
            "sku": sale.sku,
            "product_name": sale.product_name,
            "quantity": sale.quantity,
            "employee_id": sale.employee_id,
            "sale_date": _format_date(sale.sale_date),
            "revenue": sale.revenue,
        } for sale in sales]
        return jsonify({"success": True, "data": sales_data})
    except Exception as e:
        return jsonify({"success": False, "message": str(e)}), 400


@app.route("/api/analysis/sales", methods=["GET"])
def get_sales_analysis():
    """获取产品销量分析"""
    try:
        analysis = system.get_sales_analysis()
        return jsonify({"success": True, "data": analysis})
    except Exception as e:
        return jsonify({"success": False, "message": str(e)}), 400


@app.route("/api/analysis/employee-quality", methods=["GET"])
def get_employee_quality_analysis():
    """获取员工工作质量分析"""
    try:
        analysis = system.get_employee_quality_analysis()
        return jsonify({"success": True, "data": analysis})
    except Exception as e:
        return jsonify({"success": False, "message": str(e)}), 400


@app.route("/api/export/payroll", methods=["GET"])
def export_payroll():
    """导出员工薪资表（CSV格式）"""
    try:
        output = io.StringIO()
        writer = csv.writer(output)
        
        # 写入表头
        writer.writerow(["员工ID", "姓名", "职位", "联系方式", "基本工资", "绩效目标", "当前绩效", "实际薪资"])
        
        # 写入数据
        for emp in system.db.employees.values():
            writer.writerow([
                emp.employee_id,
                emp.name,
                emp.role,
                emp.contact,
                emp.base_salary,
                emp.performance_target,
                emp.performance_score,
                emp.salary(),
            ])
        
        output.seek(0)
        filename = f"员工薪资表_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
        
        return send_file(
            io.BytesIO(output.getvalue().encode('utf-8-sig')),
            mimetype='text/csv; charset=utf-8-sig',
            as_attachment=True,
            download_name=filename
        )
    except Exception as e:
        return jsonify({"success": False, "message": str(e)}), 400


@app.route("/api/export/sales-analysis", methods=["GET"])
def export_sales_analysis():
    """导出产品销量分析（CSV格式）"""
    try:
        analysis = system.get_sales_analysis()
        output = io.StringIO()
        writer = csv.writer(output)
        
        # 写入总体统计
        writer.writerow(["产品销量分析报告"])
        writer.writerow([f"生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"])
        writer.writerow([])
        writer.writerow(["总体统计"])
        writer.writerow(["总销量", "总销售额"])
        writer.writerow([analysis["total_sales"], analysis["total_revenue"]])
        writer.writerow([])
        
        # 按产品统计
        writer.writerow(["按产品统计"])
        writer.writerow(["SKU", "产品名称", "销量", "销售额"])
        for sku, data in sorted(analysis["by_product"].items(), key=lambda x: x[1]["quantity"], reverse=True):
            writer.writerow([sku, data["name"], data["quantity"], data["revenue"]])
        writer.writerow([])
        
        # 按类别统计
        writer.writerow(["按类别统计"])
        writer.writerow(["类别", "销量", "销售额"])
        for category, data in sorted(analysis["by_category"].items(), key=lambda x: x[1]["quantity"], reverse=True):
            writer.writerow([category, data["quantity"], data["revenue"]])
        writer.writerow([])
        
        # 按员工统计
        writer.writerow(["按员工统计"])
        writer.writerow(["员工ID", "员工姓名", "销量", "销售额"])
        for emp_id, data in sorted(analysis["by_employee"].items(), key=lambda x: x[1]["revenue"], reverse=True):
            writer.writerow([emp_id, data["name"], data["quantity"], data["revenue"]])
        
        output.seek(0)
        filename = f"产品销量分析_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
        
        return send_file(
            io.BytesIO(output.getvalue().encode('utf-8-sig')),
            mimetype='text/csv; charset=utf-8-sig',
            as_attachment=True,
            download_name=filename
        )
    except Exception as e:
        return jsonify({"success": False, "message": str(e)}), 400


@app.route("/api/export/employee-quality", methods=["GET"])
def export_employee_quality():
    """导出员工工作质量分析（CSV格式）"""
    try:
        analysis = system.get_employee_quality_analysis()
        output = io.StringIO()
        writer = csv.writer(output)
        
        # 写入表头
        writer.writerow([
            "员工ID", "姓名", "职位", "销售次数", "总销售额", "平均销售额",
            "绩效目标", "当前绩效", "完成率(%)", "质量评级", "基本工资", "实际薪资"
        ])
        
        # 写入数据
        for item in analysis:
            writer.writerow([
                item["employee_id"],
                item["name"],
                item["role"],
                item["total_sales"],
                item["total_revenue"],
                round(item["avg_sale_value"], 2),
                item["performance_target"],
                item["performance_score"],
                item["completion_rate"],
                item["quality_grade"],
                item["base_salary"],
                item["actual_salary"],
            ])
        
        output.seek(0)
        filename = f"员工工作质量分析_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
        
        return send_file(
            io.BytesIO(output.getvalue().encode('utf-8-sig')),
            mimetype='text/csv; charset=utf-8-sig',
            as_attachment=True,
            download_name=filename
        )
    except Exception as e:
        return jsonify({"success": False, "message": str(e)}), 400


@app.route("/")
def index():
    """返回前端页面"""
    return app.send_static_file('index.html')


if __name__ == "__main__":
    app.run(debug=True, host="0.0.0.0", port=5000)

